<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\common\support;

use app\common\support\Wechat as SysWechat;
use think\exception\ValidateException;
use think\facade\Session;
use Xin\Thinkphp5\Hint\Facade\Hint;

final class WechatQRcodeLogin{

	/**
	 * 检查登录状态
	 *
	 * @return mixed
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function check(){
		$qrcode = Session::get('qrcode_login');
		if(empty($qrcode) || !QRcodeLogin::check(md5($qrcode['ticket']), $uid)){
			throw new ValidateException("登录二维码已失效！", 40000);
		}

		if(!$uid){
			Hint::outputSuccess('等待扫码登录！', '', ['status' => 0]);
		}

		return $uid;
	}

	/**
	 * 生成一个微信二维码
	 *
	 * @param string $key
	 * @param int    $from
	 * @param int    $expire
	 * @return string
	 */
	public static function make($key, $from = 0, $expire = 300){
		$w = SysWechat::getOfficial();

		$qrcode = $w->qrcode->temporary($key, 300);
		Session::set('qrcode_login', $qrcode);

		$token = md5($qrcode['ticket']);
		QRcodeLogin::make($token, 0);

		return $w->qrcode->url($qrcode['ticket']);
	}
}
